﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddLayoutRecord.aspx.cs" Inherits="ZX.WebApp.Crm.Customer.AddLayoutRecord" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" />
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" />
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" />
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" />
    <link rel="stylesheet" type="text/css" href="../../Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" />
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/element/element-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/datasource/datasource-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/json/json-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/connection/connection-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/get/get-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/dragdrop/dragdrop-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/datatable/datatable-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/paginator/paginator-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/layout/layout-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/button/button-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/container/container-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/resize/resize-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/event-delegate/event-delegate-min.js"></script>
    <script src="../../Scripts/jquery-1.6.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.json-2.2.js" type="text/javascript"></script>
    <script src="../../Scripts/Jquery.form.js" type="text/javascript"></script>
    <script src="../../Scripts/CombinButton.js" type="text/javascript"></script>
    <script src="../../Scripts/extend.validate.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.calendar.js" type="text/javascript"></script>
    <link href="../../Styles/default/calendar.css" rel="stylesheet" type="text/css" />
    <link href="../../Styles/base.css" rel="stylesheet" type="text/css" />
    <link href="../../Styles/extendTable.css" rel="stylesheet" type="text/css" />
</head>
<body class="yui-skin-sam" onkeydown="PreventBSK()">
    <form id="form1" runat="server">
    <div>
        <div id="toolbar" style="margin-top: 12px; text-align: center;">
            <button type="button" id="btnSave" name="btnSave">
                保存</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <button type="button" id="btnClose" name="btnClose">
                取消</button>
        </div>
        <div class="fieldForm" id="fieldForm">
            <div id="content">
            <h3>
                    客户基本信息</h3>
            <table class="table1">
                <tr>
                    <th>
                        <span style="color: Red;">*</span><span>客户名称</span>
                    </th>
                    <td>
                        <input type="hidden" id="CustomerID" name="CustomerID" runat="server" />
                            <input type="text" id="txtCustomerID" runat="server" name="txtCustomerID" readonly="readonly"
                                class="width60" />
                            <button id="btnCustomerID" name="FQ" type="button" runat="server" class="btnCheck"
                                style="height: 25px;">
                                选择</button>
                    </td>
                    <th>
                        <span>客户编码</span>
                    </th>
                    <td>
                        <input runat="server" type="text" id="txtCode" name="txtCode" readonly="readonly" class="width60" />
                    </td>
                </tr>
                <tr>
                    <th>
                        <span>客户经理</span>
                    </th>
                    <td>
                        <input type="text" runat="server" id="txtCustomerMgr" name="txtCustomerMgr" readonly="readonly" class="width60" />
                    </td>
                    <th>
                        <span style="color: Red;">*</span><span>状态</span>
                    </th>
                    <td>
                        <asp:DropDownList ID="State" name="State" runat="server" CssClass="width65"
                                AppendDataBoundItems="true">
                                <asp:ListItem Value=""></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
            </table>
            </div>
            <div class="extendDiv">
                <div id="con_two_1">
                    <h3>
                        产品信息
                        <button type="button" id="btnNew1" name="btnNew1">
                            新增</button>
                        <button type="button" id="btnDelete1" name="btnDelete1">
                            删除</button>
                    </h3>
                    <div id="con_1">
                    </div>
                </div>
                <div class="TotalMoneyDiv">
                    <span>总成交额</span>
                    <input type="text" runat="server" id="TotalMoney" name="TotalMoney"  readonly="readonly"
                        onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')"
                        style="width: 70px;" />
                    <span=>总未交付数</span>
                    <input type="text" runat="server" id="TotalNoPayCount" name="TotalNoPayCount" readonly="readonly"
                        onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')"
                        style="width: 70px;" />
                    <span=>总到款金额</span>
                    <input type="text" runat="server" id="TotalPayMoney" name="TotalPayMoney" readonly="readonly"
                        onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')"
                        style="width: 70px;" />
                </div>
            </div>
        </div>
        <div id="dialog1" class="yui-pe-content">
            <div class="hd">
                客户选择</div>
            <div class="bd">
                <iframe id="EditUIWindow1" frameborder="0" src="" style="width: 100%; height: 100%;
                    margin: 0px; padding: 0px;"></iframe>
            </div>
        </div>
        <input type="hidden" id="ID" runat="server" />
    </div>
    </form>
    <form id="form2" style="display: none" action="../../Extend/AjaxData/CustomOperating.aspx">
    <textarea style="display: none" id="jsonDataContent" rows="2" cols="2" name="jsonDataContent"></textarea>
    </form>
</body>
<script type="text/javascript">
    var Url = "../../Extend/AjaxData/CustomOperating.aspx";
    var btnSave, btnClose, btnNews1, btnDelete1, myDataSource1, myDataTable1;
    var _ProductList = [], _PageLoadProductList = [], 
        _Flag = getPar1("flag"), tempState = 0;
    var ProductPack = [<%=ProductPack %>],
        UnitData = [<%=ListUnitId %>],
        StateData = [<%=ListState %>];
    (function () {
        //debugger
        var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event;
        Event.onDOMReady(function () {
            var layout = new YAHOO.widget.Layout({
                units: [
                { position: 'bottom', height: 60, body: 'toolbar', gutter: '1 1 1 1', scroll: null, zIndex: 2 },
                { position: 'center', body: 'fieldForm', gutter: '0 1 1 1', scroll: true }
                ]
            });
            layout.render();
        });
    })();

    //关闭当前页
    var Close = function () {
        window.parent.$("#tabs").tabs('close', '<%=PageTitle %>');
    }


    $(document).ready(function(){
        GetStated(_Flag);
    });
    YAHOO.example.init = function () {
        function onButtonClick(p_oEvent) {
            switch (this.get("id")) {
                case "btnSave":
                    Save(_Flag);
                    break;
                case "btnClose":
                    Close();
                    break;
                case "btnNew1":
                    handleAdd();
                    break;
                case "btnDelete1":
                    handleDelete();
                    break;
                default:
                    break;
            }
        }
        YAHOO.util.Event.onContentReady("toolbar", function () {
            btnSave = new YAHOO.widget.Button("btnSave");
            btnSave.on("click", onButtonClick);
            btnClose = new YAHOO.widget.Button("btnClose");
            btnClose.on("click", onButtonClick);
            btnNews1 = new YAHOO.widget.Button("btnNew1");
            btnNews1.on("click", onButtonClick);
            btnDeletes1 = new YAHOO.widget.Button("btnDelete1");
            btnDeletes1.on("click", onButtonClick);
        });
    } ();
    YAHOO.util.Event.addListener(window, "load", function () {
        BindData();
        hideCol();
    });

    var formatProductId =function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' name='ProductId' style='width:100%;'>";
    }
    var elCellPack="", oRecordPack = "", oColumnPack = "", sDataPack = "";
    var formatProductPackId = function (elCell, oRecord, oColumn, sData) {
        elCellPack = elCell, oRecordPack = oRecord, oColumnPack = oColumn, sDataPack = sData;
        var str1 = [];
        var id = "id" + Math.random();
        str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='ProductPackId' style='width:100%;'>");
        str1.push("<option value='00'> </option>");
        //debugger
        for (var i = 0; i < ProductPack.length; i++) {
            if (ProductPack[i].ID == sData) {
                str1.push("<option value='" + ProductPack[i].ID + "' selected>" + ProductPack[i].Packname + "</option>");
            } else {
                str1.push("<option value='" + ProductPack[i].ID + "'>" + ProductPack[i].Packname + "</option>");
            }
        }
        str1.push("</select>");
        elCell.innerHTML = str1.join("");
    }
    var elCells = "", oRecords = "", oColumns = "", sDatas = "";
    var formatProduct = function (elCell, oRecord, oColumn, sData) {
        elCells = elCell, oRecords = oRecord, oColumns = oColumn;
        var str1 = [];
        var id = "id" + Math.random();
        str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='ProductName' style='width:100%;'>");
        str1.push("<option value='00'> </option>");
        //debugger
        if (tempState == 1) {
            for (var i = 0; i < _PageLoadProductList.length; i++) {
                if (_PageLoadProductList[i].ProductName == sData) {
                    str1.push("<option value='" + _PageLoadProductList[i].ProductId + "' selected>" + _PageLoadProductList[i].ProductName + "</option>");
                } else {
                    str1.push("<option value='" + _PageLoadProductList[i].ProductId + "'>" + _PageLoadProductList[i].ProductName + "</option>");
                }
            }
        } else {
            for (var i = 0; i < _ProductList.length; i++) {
                if (_ProductList[i].ProductId == sData) {
                    str1.push("<option value='" + _ProductList[i].ProductId + "' selected>" + _ProductList[i].Caption + "</option>");
                } else {
                    str1.push("<option value='" + _ProductList[i].ProductId + "'>" + _ProductList[i].Caption + "</option>");
                }
            }
        }
        str1.push("</select>");
        elCell.innerHTML = str1.join("");
    }
    var formatAmount = function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='Amount' style='width:95%;'>";
    }
    var formatRebate = function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='Rebate' style='width:95%;'>";
    }
    var formatUnitId = function (elCell, oRecord, oColumn, sData) {
        var str1 = [];
        var id = "id" + Math.random();
        str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='UnitId' style='width:100%;'>");
        str1.push("<option value='00'> </option>");
        for (var i = 0; i < UnitData.length; i++) {
            if (UnitData[i].PhraseID == sData) {
                str1.push("<option value='" + UnitData[i].PhraseID + "' selected>" + UnitData[i].PhraseText + "</option>");
            } else {
                str1.push("<option value='" + UnitData[i].PhraseID + "'>" + UnitData[i].PhraseText + "</option>");
            }
        }
        str1.push("</select>");
        elCell.innerHTML = str1.join("");
    }
    var formatMoney = function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='Money' style='width:95%;'>";
    }
    var formatNoPayCount = function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='NoPayCount' style='width:95%;'>";
    }
    var formatPayMoney = function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' onchange='ChangeEvent1(this);' name='PayMoney' style='width:95%;'>";
    }
    var formatPayDate = function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" onchange='ChangeEvent1(this);' name='PayDate' style='width:95%;'>";
    }
    var formatRemark = function (elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" onchange='ChangeEvent1(this);' name='Remark' style='width:100%;'>";
    }
    var BindData = function () {
        YAHOO.example.InlineCellEditing = function () {
            var myColumnDefs1 = [
            { key: "ID", label: "ID", resizeable: true },
            { key: "ProductId", label: "ProductId", resizeable: true, formatter: formatProductId },
            { key: "ProductPackId", label: "产品包", resizeable: true, formatter: formatProductPackId },
            { key: "ProductName", label: "产品名称", resizeable: true, formatter: formatProduct, width: 150 },
            { key: "Amount", label: "成交量", resizeable: true, formatter: formatAmount, width: 70,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "Rebate", label: "折扣率", resizeable: true, formatter: formatRebate, width: 70,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "UnitId", label: "单位", resizeable: true, formatter: formatUnitId, width: 50 },
            { key: "Money", label: "成交金额", resizeable: true, formatter: formatMoney, width: 80,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "NoPayCount", label: "未交付数量", resizeable: true, formatter: formatNoPayCount, width: 80,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "PayMoney", label: "到款金额", resizeable: true, formatter: formatPayMoney, width: 80,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })
            },
            { key: "PayDate", label: "最后到款日期", resizeable: true, formatter: formatPayDate, width: 100 },
            { key: "Remark", label: "备注", resizeable: true, formatter: formatRemark, width: 150}];
            myDataSource1 = new YAHOO.util.DataSource([{ ID: "", ProductId: "", ProductPackId: "", ProductName: "", Amount: "",
                Rebate: "", UnitId: "", Money: "", NoPayCount: "", PayMoney: "", PayDate: "", Remark: ""
            }]);
            myDataSource1.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
            myDataSource1.responseSchema = {
                fields: ["ID", "ProductId", "ProductPackId", "ProductName", "Amount",
            "Rebate", "UnitId", "Money", "NoPayCount", "PayMoney", "PayDate", "Remark"]
            };
            var myDataTable1 = new YAHOO.widget.ScrollingDataTable("con_1",
            myColumnDefs1, myDataSource1, { width: "99.8%", height: "100%", selectionMode: "single" });
            mDataTable1 = myDataTable1;
            var i1 = 1,
            bReverseSorted1 = false;
            var trackReverseSorts1 = function (oArg) {
                bReverseSorted1 = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
            };
            var onCellClick = function (e) {
                var ctrl = event.srcElement || e;
                if (ctrl.nodeName == "DIV") {

                }
            }
            var onEventSaveCellEditor = function (oArgs) {
                setValue1(oArgs.editor._oColumn.key, oArgs.newData);
            }
            myDataTable1.subscribe("rowMouseoverEvent", myDataTable1.onEventHighlightRow);
            myDataTable1.subscribe("rowMouseoutEvent", myDataTable1.onEventUnhighlightRow);
            myDataTable1.subscribe("rowClickEvent", myDataTable1.onEventSelectRow);  //mousedown
            myDataTable1.subscribe("cellClickEvent", myDataTable1.onEventShowCellEditor);
            myDataTable1.subscribe("editorSaveEvent", onEventSaveCellEditor);
            myDataTable1.subscribe("cellClickEvent", onCellClick);
            myDataTable1.subscribe("checkboxClickEvent", function (oArgs) {
                var elCheckbox = oArgs.target;
                var oRecord = this.getRecord(elCheckbox);
                oRecord.setData("iSun_Selected", elCheckbox.checked);
            });
            return {
                ds: myDataSource1,
                dt: myDataTable1
            };
        } ();
    }
    //设置值
    //var GetFormValue = function () {
        //for(var i=0;i<ListRecordProduct.length;i++){
        //    SetFormValue(ListRecordProduct);
        //}
    //}
    var SetFormValue = function (obj) {
        var arr = eval(obj);
        myDataSource1.liveData = arr;
        mDataTable1.getDataSource().sendRequest(null, { success: mDataTable1.onDataReturnInitializeTable }, mDataTable1);
    }
    //隐藏/栏位
    function hideCol() {
        mDataTable1.hideColumn(parseInt(0)); mDataTable1.refreshView();
        mDataTable1.hideColumn(parseInt(1)); mDataTable1.refreshView();
    }
    //新增行
    var handleAdd = function () {
        mDataTable1.set("sortedBy", null);
        index = mDataTable1.getRecordSet()._records.length;
        var entity = [{ ID: "", ProductId: "", ProductPackId: "", ProductName: "", Amount: "",
                    Rebate: "", UnitId: "", Money: "", NoPayCount: "", PayMoney: "", PayDate: "", Remark: ""
        }];
        mDataTable1.addRows(entity, index);
    }
    //产品删除行
    var handleDelete = function () {
        //debugger
        var recordID = mDataTable1.getSelectedRows()[0];
        if (recordID != null && recordID.length != 1) {
            var RecordId = $("#ID").val();
            var record = mDataTable1.getRecord(recordID);
            var vid = record.getData("ID");
            if (vid == "" || vid == "00000000-0000-0000-0000-000000000000") {
                mDataTable1.deleteRow(recordID);
                ResetTotolMoney();
            } else {
                if (confirm("是否确定删除该行?")) {
                    var SaveUrl = Url + "?r=" + Math.random() + "&action=delete&entity=CrmLayoutRecord&json=&rid=" + RecordId + "&id=" + vid;
                    YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                        success: function (res) {
                            try {
                                var str = res.responseText;
                                if (str == "1") {
                                    alert("删除成功!");
                                    mDataTable1.deleteRow(recordID);
                                    ResetTotolMoney();
                                }
                                else {
                                    alert(str + "\n" + "数据删除失败!");
                                    return;
                                }
                            }
                            catch (e) {
                            }
                            finally {
                            }
                        },
                        failure: function (error) {
                            alert("数据错误：" + error.statusText);
                        }
                    }, null);
                }
            }
        } else {
            alert("请选中一行后删除！");
        }
    }
    var ResetTotolMoney = function () {
        var listMoney = mDataTable1.getRecordSet()._records;
        var cValueData1 = 0, cValueData2 = 0, cValueData3 = 0;
        for (var i = 0; i < listMoney.length; i++) {
            if (listMoney[i]._oData.Money != "") {
                var v1 = parseFloat(listMoney[i]._oData.Money);
                cValueData1 += v1;
            }
            if (listMoney[i]._oData.NoPayCount != "") {
                var v2 = parseFloat(listMoney[i]._oData.NoPayCount);
                cValueData2 += v2;
            }
            if (listMoney[i]._oData.PayMoney != "") {
                var v3 = parseFloat(listMoney[i]._oData.PayMoney);
                cValueData3 += v3;
            }
        }
        $('#TotalMoney').val(cValueData1.toFixed(2));
        $('#TotalNoPayCount').val(cValueData2.toFixed(2));
        $('#TotalPayMoney').val(cValueData3.toFixed(2));
    }
    //值改变事件
    var ChangeEvent1 = function (oArgs) {
        var f = oArgs.name;
        var v = oArgs.value;
        setValue1(f, v);
    }
    //f=字段名 v=值
    var record;
    var setValue1 = function (f, v) {
        var recordID = mDataTable1.getSelectedRows()[0];
        if (recordID != null && recordID.length != 1) {
            record = mDataTable1.getRecord(recordID);
            record._oData[f] = v;
            //debugger
            if (f == "ProductPackId") {
                LoadProductDataByPackId(v);
            }
            if (f == "ProductName") {
                record._oData.ProductId = v;
            }
            if (f == "Money") {
                var listMoney = mDataTable1.getRecordSet()._records;
                var cValueData = 0;
                for (var i = 0; i < listMoney.length; i++) {
                    if (listMoney[i]._oData.Money != "") {
                        var v = parseFloat(listMoney[i]._oData.Money);
                        cValueData += v;
                    }
                }
                $('#TotalMoney').val(cValueData.toFixed(2));
            }
            if (f == "NoPayCount") {
                var listTotalNoPayCount = mDataTable1.getRecordSet()._records;
                var cValueData = 0;
                for (var i = 0; i < listTotalNoPayCount.length; i++) {
                    if (listTotalNoPayCount[i]._oData.NoPayCount != "") {
                        var v = parseFloat(listTotalNoPayCount[i]._oData.NoPayCount);
                        cValueData += v;
                    }
                }
                $('#TotalNoPayCount').val(cValueData.toFixed(2));
            }
            if (f == "PayMoney") {
                var listTotalPayMoney = mDataTable1.getRecordSet()._records;
                var cValueData = 0;
                for (var i = 0; i < listTotalPayMoney.length; i++) {
                    if (listTotalPayMoney[i]._oData.PayMoney != "") {
                        var v = parseFloat(listTotalPayMoney[i]._oData.PayMoney);
                        cValueData += v;
                    }
                }
                $('#TotalPayMoney').val(cValueData.toFixed(2));
            }
        } else {
            alert("请先选中当前行!");
        }
    }

    //客户选择对应的方法和ID
    var _fn, _id;
    function ShowDialog(fn, id, src) {
        _fn = fn;
        _id = id;
        document.getElementById("EditUIWindow1").src = src;
        YAHOO.example.container.dialog1.show();
    }
    YAHOO.namespace("example.container");
    YAHOO.util.Event.onDOMReady(function () {
        var handleSubmit = function () {
            //debugger
            var editwindow = document.getElementById("EditUIWindow1");
            if (editwindow) {
                editwindow.contentWindow.ChooseInfo();
            }
            YAHOO.example.container.dialog1.hide();
        };
        var handleCancel = function () {
            this.cancel();
        };
        var handleSuccess = function (o) {
            var response = o.responseText;
            response = response.split("<!")[0];
            document.getElementById("resp").innerHTML = response;
        };
        var handleFailure = function (o) {
            alert("Submission failed: " + o.status);
        };
        YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
					            { width: "650px",
					                height: "400px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                modal: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
        YAHOO.example.container.dialog1.callback = { success: handleSuccess, failure: handleFailure };
        YAHOO.example.container.dialog1.render();
        //拖动大小dialog1
        var resize1 = new YAHOO.util.Resize("dialog1", {
            handles: ["br"],
            autoRatio: false,
            minWidth: 450,
            minHeight: 300,
            status: false
        });
        resize1.on("startResize", function (args) {
            if (this.cfg.getProperty("constraintoviewport")) {
                var D = YAHOO.util.Dom;
                var clientRegion = D.getClientRegion();
                var elRegion = D.getRegion(this.element);
                resize1.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
                resize1.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            } else {
                resize1.set("maxWidth", null);
                resize1.set("maxHeight", null);
            }

        }, YAHOO.example.container.dialog1, true);
        resize1.on("resize", function (args) {
            var panelHeight = args.height;
            this.cfg.setProperty("height", panelHeight + "px");
        }, YAHOO.example.container.dialog1, true);
    });

    var GetStated = function (_flag) {
        if (_flag == 0) { //新增
            $("#State").attr("disabled", "true");
            $("#State").get(0).selectedIndex = 1;
        } else if (_flag == 1) { //修改
            tempState=1;
            var vId=getPar1("id");
            LoadProductDataById(vId);
            LoadDetailData(vId);
        }
    }
    //修改加载数据
    var LoadDetailData = function (_id) {
        var condition = "LayoutRecordId='" + _id + "'";
        YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmLayoutRecordProducts&customCondition=" + condition + "",
        { success: function (res) {
            try {
                //debugger
                var str = res.responseText;
                var obj = eval(str);
                if (obj.length > 0) {
                    $("#CustomerID").val(obj[0].CustomerId);
                    $("#txtCustomerID").val(obj[0].CustomerName);
                    $("#txtCode").val(obj[0].Code);
                    $("#txtCustomerMgr").val(obj[0].CustomerMgrName);
                    $("#TotalMoney").val(obj[0].TotalMoney);
                    $("#TotalNoPayCount").val(obj[0].TotalNoPayCount);
                    $("#TotalPayMoney").val(obj[0].TotalPayMoney);
                    for (var j = 0; j < StateData.length; j++) {
                        if (obj[0].State == StateData[j].PhraseID) {
                            $("#State").get(0).selectedIndex = j + 1;
                        }
                    }
                    if (obj[0].ID != "" && obj[0].ID != "00000000-0000-0000-0000-000000000000") {
                        SetFormValue(obj);
                    }
                }
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
        });
    }
    
    //根据产品包ID加载产品信息
    var LoadProductDataByPackId = function (packId) {
        var condition = "PackID='" + packId + "'";
        YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmPackDetail&customCondition=" + condition + "",
        { success: function (res) {
            try {
                //debugger
                var str = res.responseText;
                var obj = eval(str);
                _ProductList = obj;
                tempState = 0;
                formatProduct(elCells, oRecords, oColumns, obj);
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
        });
    }
    //加载数据显示产品信息
    var LoadProductDataById = function (_Id) {
        var condition = "LayoutRecordId='" + _Id + "'";
        YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmLayoutRecordProducts&customCondition=" + condition + "",
        { success: function (res) {
            try {
                //debugger
                var str = res.responseText;
                var obj = eval(str);
                _PageLoadProductList = obj;
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
        });
    }
    //保存数据
    var Save = function (flag) {
        //debugger
        var instance = [{ ID: "", CustomerId: "", State: "", TotalMoney: "", TotalNoPayCount: "", TotalPayMoney: "", ListData: ""}];

        var CustomerID = $("#CustomerID").val();
        var State = $("#State").val();
        var TotalMoney = $("#TotalMoney").val();
        var TotalNoPayCount = $("#TotalNoPayCount").val();
        var TotalPayMoney = $("#TotalPayMoney").val();
        if (CustomerID == "") {
            alert("客户名称不能为空!");
            return;
        }
        if(State==""||State=="00000000-0000-0000-0000-000000000000"){
            alert("状态不能为空!");
            return;
        }

        var list = mDataTable1.getRecordSet()._records;
        var elist = [];
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.ID == "" || list[i]._oData.ID == null) {
                list[i]._oData.ID = "00000000-0000-0000-0000-000000000000";
            }
            if (list[i]._oData.ProductPackId == "" || list[i]._oData.ProductPackId == null || list[i]._oData.ProductPackId == "00") {
                alert("第" + (i + 1) + "行 产品包不能为空!");
                return;
            }
            if (list[i]._oData.ProductId == "" || list[i]._oData.ProductId == null || list[i]._oData.ProductPackId == "00") {
                alert("第" + (i + 1) + "行 产品名称不能为空!");
                return;
            }
            if (list[i]._oData.Amount == "" || list[i]._oData.Amount == null) {
                alert("第" + (i + 1) + "行 成交量不能为空!");
                return;
            }
            if (list[i]._oData.Rebate == "" || list[i]._oData.Rebate == null) {
                alert("第" + (i + 1) + "行 折扣率不能为空!");
                return;
            }
            if (list[i]._oData.UnitId == "" || list[i]._oData.UnitId == null || list[i]._oData.UnitId == "00") {
                alert("第" + (i + 1) + "行 单位不能为空!");
                return;
            }
            if (list[i]._oData.Money == "" || list[i]._oData.Money == null) {
                alert("第" + (i + 1) + "行 成交金额不能为空!");
                return;
            }
            if (list[i]._oData.NoPayCount == "" || list[i]._oData.NoPayCount == null) {
                alert("第" + (i + 1) + "行 未交付数量不能为空!");
                return;
            }
            if (list[i]._oData.PayMoney == "" || list[i]._oData.PayMoney == null) {
                alert("第" + (i + 1) + "行 到款金额不能为空!");
                return;
            }
            if (list[i]._oData.PayDate == "" || list[i]._oData.PayDate == null) {
                alert("第" + (i + 1) + "行 最后到款日期不能为空!");
                return;
            }
            elist.push(list[i]._oData);
        }
        for (var j = 0; j < elist.length; j++) {
            instance[0].ListData += "@" + elist[j].ID + "︾" + elist[j].ProductPackId + "︾" + elist[j].ProductId + "︾" +
                                            elist[j].Amount + "︾" + elist[j].Rebate + "︾" + elist[j].UnitId + "︾" +
                                            elist[j].Money + "︾" + elist[j].NoPayCount + "︾" + elist[j].PayMoney + "︾" +
                                            elist[j].PayDate + "︾" + elist[j].Remark + "︾";
        }
        if (TotalMoney == "") {
            alert("总成交额不能为空!");
            return;
        }
        if (TotalNoPayCount == "") {
            alert("总未交付数不能为空!");
            return;
        }
        if (TotalPayMoney == "") {
            alert("总到款金额不能为空!");
            return;
        }
        instance[0].ID = $("#ID").val();
        instance[0].State=State;
        instance[0].CustomerId = CustomerID;
        instance[0].TotalMoney = TotalMoney;
        instance[0].TotalNoPayCount = TotalNoPayCount;
        instance[0].TotalPayMoney = TotalPayMoney;
        //debugger
        var json = $.toJSON(instance[0]).replace(/'/g, "[B]");
        $("#jsonDataContent").val(json);
        if(confirm("是否确定保存?")){
            trySave(flag);
        }
    }
    var trySave = function (flag) {
        var formObject = document.getElementById('form2');
        YAHOO.util.Connect.setForm(formObject);
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&action=insert&entity=CrmLayoutRecord", callback);
    }
    var responseSuccess = function (res) {
        try {
            //debugger
            var str = res.responseText;
            if (str == "1") {
                alert("数据保存成功");
                RefreshDataParent(); //刷新父页面
                Close();  //关闭当前页
            } else {
                alert(str);
            }
        } catch (e) {
        }
        finally {
        }
    }
    var responseFailure = function (error) {
        alert("数据错误：" + error.statusText);
    }
    var callback = {
        success: responseSuccess,
        failure: responseFailure
    }
    //刷新父窗体数据
    function RefreshDataParent() {
        if (parent.NeedRefreshPage != null) {
            if (typeof (parent.NeedRefreshPage.LoadData) == "function") {
                parent.NeedRefreshPage.RefreshData();
            }
        }
    }
</script>
</html>
